//
//  TZConnection.m
//  TZGroup
//
//  Created by mini on 13-4-2.
//  Copyright (c) 2013年 hjj. All rights reserved.
//

#import "XLConnection.h"
#import "XLHTTPClent.h"
#import "XLResponse.h"

typedef void(^CompletionBlock)(XLConnection *, XLResponse *, NSError *);
static NSMutableDictionary *queue;
static UIWindow *indicatorWindow;
@interface XLConnection() {
    NSMutableDictionary *_dataDict;
}
@property (nonatomic) SEL actionForSuccess;
@property (nonatomic) SEL actionForFailure;
@property (weak, nonatomic) id delegate;
@property (strong, nonatomic) CompletionBlock completionBlock;
@end
@implementation XLConnection

+ (BOOL)isSuccessReturn:(NSDictionary *)returnDict
{
    return [[returnDict objectForKey:kStatusKey] integerValue] == 1;
}

- (id)initWithDelegate:(id)delegate actionForSuccess:(SEL)success actionForFailure:(SEL)failure
{
    self = [super init];
    if (self) {
        _delegate = delegate;
        _actionForSuccess = success;
        _actionForFailure = failure;
        if (!queue) {
            queue = [NSMutableDictionary dictionary];
        }
        [queue setObject:self forKey:[NSString stringWithFormat:@"%p", self]];
    }
    return self;
}
- (id)initWithCompletionBlock:(void (^)(XLConnection *, XLResponse *, NSError *))completionBlock
{
    self = [super init];
    if (self) {
        _completionBlock = completionBlock;
    }
    [queue setObject:self forKey:[NSString stringWithFormat:@"%p", self]];
    return self;
}

- (void)requestFinished:(AFHTTPRequestOperation *)operation withResponse:(id)responseObject error:(NSError *)error
{
    [queue removeObjectForKey:[NSString stringWithFormat:@"%p", self]];
    if (self.needIndicator) {
        indicatorWindow.hidden = YES;
        id<UIApplicationDelegate> delegate = [UIApplication sharedApplication].delegate;
        [delegate.window makeKeyAndVisible];
    }
    XLResponse *response;
    NSDictionary *returnDict = [self getJsonWithData:responseObject];
    if (returnDict) {
        response = [[XLResponse alloc] init];
        response.status = [[returnDict objectForKey:kStatusKey] description];
        response.message = [returnDict objectForKey:kMessageKey];
        response.result = [returnDict objectForKey:kResultKey];
    }
    __weak XLConnection *wself = self;
    if (wself.completionBlock) {
        (wself.completionBlock)(wself, response, error);
    }
}
- (BOOL)canEndIndicator
{
    for (XLConnection *connection in queue.allValues) {
        if (self == connection) {
            continue;
        }
        if (connection.needIndicator) {
            return NO;
        }
    }return YES;
}

- (UIWindow *)createIndicatorWindow
{
    UIWindow *fWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
    fWindow.backgroundColor = [UIColor clearColor];
    fWindow.windowLevel = UIWindowLevelNormal + 1;
    fWindow.rootViewController = [[UIViewController alloc] init];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
    fWindow.rootViewController.view = view;
    UIView *bgView= [[UIView alloc] initWithFrame:CGRectMake(552, 304, 100, 100)];
    bgView.backgroundColor = [UIColor blackColor];
    bgView.alpha = 0.6;
    bgView.layer.cornerRadius = 15;
    [view addSubview:bgView];
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    indicator.alpha = 1;
    indicator.frame = CGRectMake(40, 28, 20, 20);
    [bgView addSubview:indicator];
    [indicator startAnimating];
    UILabel *lbLoading = [[UILabel alloc]initWithFrame:CGRectMake(9, 58, 82, 20)];
    [lbLoading setBackgroundColor:[UIColor clearColor]];
    [lbLoading setTextAlignment:NSTextAlignmentCenter];
    [lbLoading setTextColor:[UIColor colorWithHexString:@"AAAAAA"]];
    [lbLoading setText:@"加载中..."];
    [lbLoading setFont:[UIFont systemFontOfSize:15]];
    [bgView addSubview:lbLoading];
    return fWindow;
}

- (void)showIndicatorWindow
{
    if (!indicatorWindow) {
        indicatorWindow = [self createIndicatorWindow];
    }
    [indicatorWindow makeKeyAndVisible];
}

- (void)getRequestWithRelativePath:(NSString *)path andParams:(NSDictionary *)params
{
    NSArray *keys = [params allKeys];
    for (int i = 0; i < keys.count; i++) {
        NSString *key = [keys objectAtIndex:i];
        path = [path stringByAppendingString:[NSString stringWithFormat:@"/%@/%@", key, [params objectForKey:key]]];
    }
    if (self.needIndicator) {
        [self showIndicatorWindow];
    }
    [[XLHTTPClent sharedClient] getPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self requestFinished:operation withResponse:responseObject error:nil];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self requestFinished:operation withResponse:nil error:error];
    }];
}
- (void)postRequestWithRelativePath:(NSString *)path andParams:(NSDictionary *)params
{
    NSString *newPath = path;
    NSArray *keys = [params allKeys];
    for (int i = 0; i < keys.count; i++) {
        NSString *key = [keys objectAtIndex:i];
        newPath = [newPath stringByAppendingString:[NSString stringWithFormat:@"/%@/%@", key, [params objectForKey:key]]];
    }
    if (self.needIndicator) {
        [self showIndicatorWindow];
    }
    [[XLHTTPClent sharedClient] postPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self requestFinished:operation withResponse:responseObject error:nil];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self requestFinished:operation withResponse:nil error:error];
    }];
}
- (NSDictionary *)getJsonWithData:(NSData *)data
{
    if (!data) {
        return nil;
    }
    NSError *error;
    id result = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments | NSJSONReadingMutableContainers) error:&error];
    if (error != nil)
        return nil;
    return result;
}
- (void)setInfoWithCode:(NSString*)_code
{
    NSString *relativeUrl = @"index.php";
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@"app" forKey:@"c"];
    [params setObject:@"getmenu" forKey:@"a"];
    [params setObject:_code forKey:@"key"];
    [self postRequestWithRelativePath:relativeUrl andParams:params];
}

- (NSString *)createPostURL:(NSDictionary *)params
{
    NSString *postString = @"";
    for (NSString *key in [params allKeys]) {
        NSString *value = [params objectForKey:key];
        postString=[postString stringByAppendingFormat:@"%@=%@&",key,value];
    }
    if ([postString length] > 1)
    {
        postString = [postString substringToIndex:[postString length] - 1];
    }
    return postString;
}

- (void)setObject:(id)object forKey:(NSString *)key
{
    if (!_dataDict) {
        _dataDict = [NSMutableDictionary dictionary];
    }
    [_dataDict setObject:object forKey:key];
}

- (id)objectForKey:(NSString *)key
{
    return [_dataDict objectForKey:key];
}

- (void)upDataWithSIDs:(NSString*)ids
{
    NSString *relativeUrl = @"index.php";
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@"app" forKey:@"c"];
    [params setObject:@"get_quanjing" forKey:@"a"];
    [params setObject:ids forKey:@"sid"];
    [self postRequestWithRelativePath:relativeUrl andParams:params];
}

- (void)checkUpdate
{
    NSString *relativeUrl = @"index.php";
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@"appupsy" forKey:@"c"];
    [self postRequestWithRelativePath:relativeUrl andParams:params];
}

- (void)postClickInfo:(NSString*)info
{
    NSString *relativeUrl = @"index.php";
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@"app" forKey:@"c"];
    [params setObject:@"checkquanjinginfo" forKey:@"a"];
    [params setObject:info forKey:@"info"];
    [self postRequestWithRelativePath:relativeUrl andParams:params];
}

@end
